package ext.tianma.bom.service;

import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;

public class MD5Util {
	
	static char hexdigits[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
	
	public static String md5Encrypt(InputStream in) {
		if (in == null) {
			return "";
		}
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] buffer = new byte[2048];
			int length = -1;
			while((length = in.read(buffer)) != -1){
				md.update(buffer, 0, length);
			}
			byte[] b = md.digest();
			return byteToHexString(b);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	private static String byteToHexString(byte[] tmp){
		String s;
		//用字节表示就是16个字节
		//每个字节用16进制表示的话，使用两个字符，所以表示成16进制需要32 个字符
		char str[] = new char[16 * 2];
		int k = 0;//表示转换结果中对应的字符位置
		//从第一个字节开始，对MD5的每一个字节转换成16进制字符的转换
		for(int i = 0; i < 16; i++){
			byte byte0 = tmp[i];
			//取字节中高4为的数字转换
			str[k++] = hexdigits[byte0 >>> 4 & 0xf];
			//取字节中低4位的数字转换
			str[k++] = hexdigits[byte0 & 0xf];
		}
		s = new String(str);
		return s;
	}
	
}
